package com.q3d.demo.svc.config.service;

import java.net.URI;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j /** Lombok 的 Logger 注解 */
/**
 * @author 叶湘 ( weixin:yexiang841, email:yexiang841@qq.com )
 */
public class PublishV1Service {

        @Autowired
        private RestTemplate restTemplate;

        @Autowired
        private DiscoveryClient discoveryClient;

        /**
         * 在没有使用消息同步队列(如 SpringCloud Bus)的情况下，手动调用各微服务的 actuator/refresh 接口刷新配置
         * 
         * @return JSONObject
         */
        public void refresh() {
                this.refreshService("admin-svc-v1", "/");
                this.refreshService("hello-svc-v1", "/");
        }

        /**
         * 调用单个微服务之下的所有副本的 actuator/refresh 接口刷新配置
         * 
         * @return JSONObject
         */
        public void refreshService(String serviceName, String contextPath) {
                // 定义 requestHeaders
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.setContentType(MediaType.APPLICATION_JSON);
                // 定义 requestBody
                MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
                // 定义 request = requestHeaders + requestBody
                HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(
                                requestBody,
                                requestHeaders);
                // 手动寻址：获取 Eureka-Server 中注册的实例列表，代替具体 {host}:{port}
                // 然后手动选择 HA 实例
                List<ServiceInstance> sericeInstanceList = discoveryClient.getInstances(serviceName);
                for (ServiceInstance serviceInstance : sericeInstanceList) {
                        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort()
                                        + contextPath + "/actuator/refresh";
                        URI uri = URI.create(url);
                        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST,
                                        request,
                                        String.class);
                        log.info(response.getBody());
                }
                return;
        }

}
